package com.chen.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;


@SuppressWarnings("deprecation")
public class HibernateSessionFactory {
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	public static final Configuration configuration = new AnnotationConfiguration();
	public static final SessionFactory sessionFactory;

	static {
		try {
			configuration.configure();
			sessionFactory = configuration.buildSessionFactory();
		} catch (Throwable ex) {
			ex.printStackTrace();
			throw new ExceptionInInitializerError(ex);
		}
	}

	private HibernateSessionFactory() {
	}

	public static Session currentSession() {
		Session session = threadLocal.get();
		if (session == null || !session.isOpen()) {
			session = (sessionFactory != null) ? sessionFactory.openSession() : null;
			threadLocal.set(session);
		}
		return session;
	}

	public static void closeSession() {
		Session session = sessionFactory.getCurrentSession();
		if (session != null) {
			session.close();
		}
		threadLocal.set(null);
	}
}
